package com.cyzy.server.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements; // 使用正确的导入

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.jsoup.nodes.Element;
import org.jsoup.nodes.Document;

import org.springframework.stereotype.Service;




@Slf4j
public class Main {

    public static void main(String[] args) {
        String url = "http://jwxt.gdufe.edu.cn/jsxsd/xk/LoginToXkLdap";
        String username = "22252502106";
        String password = "15820223576xue";
        String randomCode = "nb3c";
        String cookieValue = "C2341972D1F8EC84606FA4E186CBF465";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 添加 Cookie 到请求头
            httpPost.setHeader("Cookie", "JSESSIONID=" + cookieValue);

            // 构建请求参数
            String requestBody = "USERNAME=" + urlEncode(username) + "&PASSWORD=" + urlEncode(password) + "&RANDOMCODE=" + urlEncode(randomCode);
            StringEntity entity = new StringEntity(requestBody);
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应状态码: " + response.getStatusLine().getStatusCode());
                //System.out.println("响应体: " + responseBody);
                String errorMessage = null;

                try {
                    // 使用Jsoup解析HTML内容
                    Document doc = Jsoup.parse(responseBody);

                    // 找到带有红色字体的标签
                    Elements elements = doc.select("font[color=red]");

                    // 提取其中的文本内容
                    if (!elements.isEmpty()) {
                        Element errorElement = elements.first();
                        errorMessage = errorElement.text();
                        System.out.println(errorMessage);
                    }
                    //System.out.println(elements);
                } catch (Exception e) {
                    e.printStackTrace();
                    // 处理异常情况
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String urlEncode(String value) throws UnsupportedEncodingException {
        return URLEncoder.encode(value, "UTF-8");
    }
}
